package com.example.teaching_server.repository;

import com.example.teaching_server.entity.UserEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface UserRepository extends JpaRepository<UserEntity, Long> {

    Optional<UserEntity> findByUsername(String username);

    List<UserEntity> findByNameContainingIgnoreCase(String name);

    List<UserEntity> findByRole(String role);

    List<UserEntity> findByClassEntityId(Long classId);

    // 从 UserRepository 合并过来的方法
    Optional<UserEntity> findById(Long id);

    List<UserEntity> findAll();

    // 复杂查询使用JPQL
    @Query("SELECT u FROM UserEntity u WHERE u.role = :role AND u.classEntity IS NOT NULL ORDER BY u.name")
    List<UserEntity> findStudentsWithClass(@Param("role") String role);

    @Query("SELECT u FROM UserEntity u JOIN u.classEntity c WHERE c.grade.gradeName = :gradeName")
    List<UserEntity> findByGradeName(@Param("gradeName") String gradeName);

    @Query("SELECT u FROM UserEntity u WHERE u.role = 'teacher' AND u.id IN " +
            "(SELECT tc.teacher.id FROM TeacherClass tc WHERE tc.classEntity.id = :classId)")
    List<UserEntity> findTeachersByClassId(@Param("classId") Long classId);

    // 从 UserRepository 合并的查询方法
    @Query("SELECT u FROM UserEntity u WHERE u.role = :role")
    List<UserEntity> findByRoleWithQuery(@Param("role") String role);

    @Query("SELECT u FROM UserEntity u WHERE u.classEntity.id = :classId")
    List<UserEntity> findByClassIdWithQuery(@Param("classId") Long classId);

    /**
     * 根据班级ID查询用户
     */
    @Query("SELECT u FROM UserEntity u WHERE u.classEntity.id = :classId")
    List<UserEntity> findByClassId(@Param("classId") Long classId);
}
